require "date"
require "lib/utils.rb"

# Read games
gamesFile = File.new(ARGV[1] ? ARGV[1] : "games.txt", "r")
games = [];
gamesFile.each_line {|line|
    games.push line
}
gamesFile.close

# Read ratings
fin = File.new(ARGV[0] ? ARGV[0] : "ratings.txt", "r")
currRatings = {}
while(line = fin.gets)	
	if(/^(.+?)\s+([\d.]+)/.match(line))		
		currRatings[$1] = $2.to_f;
	end
end
fin.close

newPlayersRatings = {};

games.each {|line|
	if(/^\s*([^<>]+\S)\s*([<>])\s*([^<>]+\S)\s*$/.match(line))		
		$winner	 = $2==">" ? $1 : $3;
		$looser = $2==">" ? $3 : $1;
				
		newPlayersRatings[$looser] = 0.0 if(!newPlayersRatings[$looser] && !currRatings[$looser]);
		newPlayersRatings[$winner] = 0.0 if(!newPlayersRatings[$winner] && !currRatings[$winner]);
		
		$looserRating = currRatings[$looser] ? currRatings[$looser] : 0.0;
		$winnerRating = currRatings[$winner] ? currRatings[$winner] : 0.0;
		$diff = $looserRating + 100.0 - $winnerRating;
		
		if($diff>0)
		   newPlayersRatings[$winner] += $diff/10 if(newPlayersRatings.keys.member?($winner));
		   newPlayersRatings[$looser] -= $diff/20 if(newPlayersRatings.keys.member?($looser));
		   #p newPlayersRatings
		   #p "*"*30
		end		
	end
}

newPlayersRatings.map{|key, val| newPlayersRatings[key] = val < 0 ? 0.0 : val }

currRatings.merge!(newPlayersRatings);
newRatings = {};
newRatings.merge!(currRatings);

games.each {|line|
	if(/^\s*([^<>]+\S)\s*([<>])\s*([^<>]+\S)\s*$/.match(line))
		$winner = $2==">" ? $1 : $3;
		$looser = $2==">" ? $3 : $1;		
		
		$diff = currRatings[$looser] + 100 - currRatings[$winner];
		next if($diff<=0);
		
		# else		
		#$diff*=2; # Uncomment to change coeff. (e.g.for Pro-tour)
		newRatings[$winner]+=$diff/10;
		newRatings[$looser]-=$diff/20;		
	end
}

$fileName = "ratings-" + (Date.today.to_s) + ".txt";

if(File.exist?($fileName))
	$i = 1;
	$fileName = "ratings-" + (Date.today.to_s) + "-" +  $i.to_s + ".txt";
	while(File.exist?($fileName))
		$i+=1;
		$fileName = "ratings-" + (Date.today.to_s) + "-" +  $i.to_s + ".txt";
	end	
end

fout = File.new($fileName, "w")
newRatings.sort{|a,b| b[1] <=> a[1]}.each {|key, value| 
	fout <<  key.to_s + " "*(20 - key.length) + format("%.4f", [value,0.0].max ) + "\n";
}
fout.close